#ifndef TCP_SOCKET_H
#define TCP_SOCKET_H
#include <string.h>
#include "base_socket.h"

class TcpSocket:public BaseSocket
{
public:
	TcpSocket(int fd,struct sockaddr_in addr,socklen_t len)
	{
		this->fd = fd;
		this->addr = addr;
		this->len = len;
	}

	TcpSocket(const char* ip,uint16_t port):BaseSocket(SOCK_STREAM,ip,port) {}
	int send(void* buf,size_t size)
	{
		return ::send(fd,buf,size,0);
	}

	int recv(void* buf,size_t size)
	{
		return ::recv(fd,buf,size,0);
	}

	int send(const char* str)
	{
		return ::send(fd,str,strlen(str)+1,0);
	}
};

class TcpServer:public TcpSocket
{
public:
	TcpServer(const char* ip,uint16_t port,int backlog=5):TcpSocket(ip,port)
	{
		if(bind(fd,(SP)&addr,len))
		{
			perror("bind");
			return;
		}

		if(listen(fd,backlog))
		{
			perror("listen");
			return;
		}
	}

	TcpSocket* accept(void)
	{
		int cli_fd = ::accept(fd,(SP)&addr,&len);
		if(0 >= cli_fd)
		{
			perror("accpet");
			return NULL;
		}

		return new TcpSocket(cli_fd,addr,len);
	}
};

class TcpClient:public TcpSocket
{
public:
	TcpClient(const char* ip,uint16_t port):TcpSocket(ip,port)
	{
		if(connect(fd,(SP)&addr,len))
		{
			perror("connect");
			return;
		}
	}
};

#endif//TCP_SOCKET_H
